package pe.edu.unmsm.fisi.sisconteg.application.security;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;

import pe.edu.unmsm.fisi.sisconteg.business.service.UsuarioService;
import pe.edu.unmsm.fisi.sisconteg.domain.model.Usuario;


public class CustomAuthenticationManager implements AuthenticationManager {

	@Resource
	private UsuarioService usuarioService;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		User user;
		Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(2);
		try {
			user = getUser((String)authentication.getPrincipal(), (String)authentication.getCredentials());
		} catch (Exception e) {
			throw new BadCredentialsException("Datos no válidos");
		}
		
		if (user != null) {
			grantedAuthorities = user.getAuthorities();
		} else {
			throw new BadCredentialsException("Datos no validos");
		}
		
		return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), grantedAuthorities);
	}

	private User getUser(String nick, String pass) {
		User user = null;
		Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(1);
		GrantedAuthority grantedAuthority;
		try {
			Usuario usuario = usuarioService.validarUsuarioyPassword(nick, pass);
			if (usuario != null) {
				String rol;
				rol = usuario.getPerfil();
				grantedAuthority = new GrantedAuthorityImpl(rol);
				grantedAuthorities.add(grantedAuthority);
				user = new User(nick, pass, true, true, true, true, grantedAuthorities);
			} else {
				grantedAuthority = new GrantedAuthorityImpl("IS_AUTHENTICATED_ANONYMOUSLY");
				grantedAuthorities.add(grantedAuthority);
				user = new User(nick, pass, true, true, true, true, grantedAuthorities);
			}
		
		} catch (Exception e) {
			throw e;
		}

		return user;
	}

}
